package config

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"todo-list/utils/yaml"
)

var appPath string

var (
	Configs    Config
	AppMode    string
	HttpPort   string
	Domain     string
	Protocols  string
	DBHost     string
	DBPort     string
	DBUser     string
	DBPassword string
	DBName     string

	RedisHost     string
	RedisPort     string
	RedisPassword string
	RedisDBName   int
)

func InitConfig() {
	//setAppPath()
	configPath := getFullPath("config/config.yaml")
	err := yaml.ReadYaml(configPath, &Configs)
	if err != nil {
		logrus.Panicf("配置文件读取失败,请检查文件路径[%s]: %s", configPath, err.Error())
	}
	err = loadLocals("zh_cn")
	if err != nil {
		logrus.Panicf("国际化读取失败,请检查: %s", err.Error())
	}
	setGinMode()
	loadServer()
	loadDB()
	loadRedis()
}

func setAppPath() {
	file, _ := exec.LookPath(os.Args[0])
	path, _ := filepath.Abs(file)
	index := strings.LastIndex(path, string(os.PathSeparator))
	appPath = path[:index]
}

func setGinMode() {
	gin.SetMode(AppMode)
}

func getFullPath(path string) string {
	if appPath == "" {
		return path
	}
	return fmt.Sprintf("%s/%s", appPath, path)
}

func loadServer() {
	AppMode = Configs.Service.GetString("AppMode")
	HttpPort = Configs.Service.GetString("HttpPort")
	Protocols = Configs.Service.GetString("Protocols")
	Domain = Configs.Service.GetString("Domain")
}

func loadRedis() {
	RedisHost = Configs.Redis.GetString("Host")
	RedisPort = Configs.Redis.GetString("Port")
	RedisPassword = Configs.Redis.GetString("Password")
	RedisDBName = Configs.Redis.GetInt("Name")
}

func loadDB() {
	DBHost = Configs.Database.GetString("Host")
	DBPort = Configs.Database.GetString("Port")
	DBUser = Configs.Database.GetString("User")
	DBPassword = Configs.Database.GetString("PassWord")
	DBName = Configs.Database.GetString("Name")
}

func Origin() string {
	return fmt.Sprintf("%s://%s:%s", Protocols, Domain, HttpPort)
}
